package org.oep.jmingle;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

public class LoadScreen extends Canvas implements Runnable {
	private MingleTracker tracker;
	private int total;
	private int DOTCOUNT = 0;
	private int DOTCOUNTMAX = 3;
	private int DOTCUR = 0;
	private int DOTMAX = 5;
	private Thread th;
	
	public LoadScreen(MingleTracker tracker) {
		this.tracker = tracker;
		this.total = tracker.countSavedDevices();
		th = new Thread(this);
		th.start();
		repaint();
	}
	
	public void run() {
		while(true) {
			try {
				repaint();
				Thread.sleep(100);
			}
			catch(Exception e) { break; }
		}
	}
	
	public void paint(Graphics g) {
		if(tracker == null) return;
		
		g.setColor(255, 255, 255);
		g.fillRect(0, 0, this.getWidth(), this.getHeight());
		g.setColor(0);
		
		int barWidthY = 5;
		int barWidthX = this.getWidth() / 2;
		int progressWidth;
		int progress;
		int num = tracker.numberOfDevices();
		
		if(num < 0) {
			progress = 0;
			progressWidth = 0;
		} 
		else if(total > 0) {
			progress = (100 * num) / total;
			progressWidth =  (barWidthX * progress) / 100;
		}
		else {
			progress = 100;
			progressWidth = barWidthX;
		}
		
		// The actual progress bar
		g.setColor(0xaaaaaa);
		if(progressWidth > 0)
			g.fillRect(this.getWidth() / 4 + 1, this.getHeight() / 2 - barWidthY / 2 + 1, progressWidth - 1, barWidthY - 1);
		
		
		
		// OMG ANIMATION
		String loadMsg = "Loading mingles";
		for(int i = 0; i < DOTCOUNT; i++) {
			loadMsg += ".";
		}
		
		DOTCUR++;
		if(DOTCUR > DOTMAX) {
			DOTCUR = 0;
			DOTCOUNT++;
		}
		
		if(DOTCOUNT > DOTCOUNTMAX)
			DOTCOUNT = 0;
		
		g.setColor(0);
		g.drawString("Loading mingles...", this.getWidth() / 2, this.getHeight() / 2 - barWidthY / 2, Graphics.BOTTOM | Graphics.HCENTER);
		
		// Other elements
		g.setColor(0);
		g.drawRect(this.getWidth() / 4, this.getHeight() / 2 - barWidthY / 2, barWidthX, barWidthY);
		
		if(num >= 0)
			g.drawString(progress + "%", this.getWidth() / 2, this.getHeight() / 2 + barWidthY / 2, Graphics.TOP | Graphics.HCENTER);
		else
			g.drawString("Waiting...", this.getWidth() / 2, this.getHeight() / 2 + barWidthY / 2, Graphics.TOP | Graphics.HCENTER);
	}
	
	public void die() {
		th.interrupt();
	}
}
